<?php
// +----------------------------------------------------------------------
// | 基础方法
// +----------------------------------------------------------------------
namespace app\common\service;

use app\common\enum\BaseStatusEnum;
use app\common\model\SysRoleMenuModel;
use app\common\service\SysMenuService;

class SysRoleMenuService{

    /**
     * 新增
     * @param  array  $data  新增的数据
     * @return int
     */
    public static function save($data){
        $res = SysRoleMenuModel::create($data);
        return $res->id;
    }

    /**
     * 批量新增
     * @param  array  $list  新增的数据
     * @return int
     */
    public static function saveAll($list){
        $model = new SysRoleMenuModel;
        $model->saveAll($list);
    }

    /**
     * 更新
     * @param  array  $data 更新的数据
     * @return int
     */
    public static function update($data){
        $role = SysRoleMenuModel::find($data['id']);
        if(!$role){
            return 0;
        }
        $role->save($data);
        return $role->id;

    }

    /**
     * 删除
     * @param  string  $ids  需要删除数据的id
     */
    public static function destroy($ids){
        if(!empty($ids)){
            SysRoleMenuModel::deleteById($ids);
        }
    }

    /**
     * 删除
     * @param  string  $roleId  角色ID
     */
    public static function destroyByRoleId($roleId){
        if(!empty($roleId)){
            SysRoleMenuModel::where('role_id', $roleId)->update(['delete_time' => date('Y-m-d H:i:s',time())]);
        }
    }

    /**
     * 分页
     * @param  array  $param 搜索条件
     * @return array
     */
    public static function page($param){
        return SysRoleMenuModel::page($param);
    }

    /**
     * 列表
     * @return array
     */
    public static function list($param){
        $model = new SysRoleMenuModel;
        if (isset($param['roleIds']) && count($param['roleIds'])) {
            $model = $model->where('role_id', 'in', $param['roleIds']);
        }

        $roleMenuList = $model->field('role_id,menu_id')->select()->toArray();
        if (empty($roleMenuList)) {
            return [];
        }

        $menuIds = array_column($roleMenuList, 'menu_id');
        $menuList = SysMenuService::list(['ids' => $menuIds, 'status' => BaseStatusEnum::ENABLED]);

        $list = [];

        foreach ($roleMenuList as $v) {
            foreach ($menuList as $vv) {
                if ($v['menu_id'] == $vv['id']) {
                    $vv['role_id'] = $v['role_id'];
                    array_push($list, $vv);
                }
            }
        }

        return $list;
    }


    /**
     * 根据角色获取列表
     * @param  array  $roleIds 角色ID
     * @return array
     */
    public static function listByRoleIds($roleIds){
        $param['status'] = BaseStatusEnum::ENABLED;
        $param['roleIds'] = $roleIds;
        return self::list($param);
    }

}